import nme.Assets;
import nme.display.Sprite;
import nme.display.Bitmap;
import nme.display.BitmapData;
import nme.display.Tilesheet;

import nme.geom.Rectangle;
import nme.geom.Matrix;
import nme.geom.Point;

import nme.events.Event;

class Animation extends Sprite
{
	private var _sprite:SpriteData;	
	private var _anim:AnimData;
	
	private var _time:Int = 0;
	private var _frameId:String = "";
	private var _currentFrame:Int = 0;
	private var _nFrame:Int = 0;
	private var _bound:Rectangle;	
	private var _animId:String;
	private var _matrix:Matrix;
	
	private var _changed:Bool;
	
	public function new (spirte:SpriteData, id:String)
	{
		super ();
		_sprite = spirte;
		_animId = id;
		_anim = _sprite._anims.get (_animId);
		
		_currentFrame = 0;
		_nFrame = _anim._frames_id.length;
		_frameId = _anim._frames_id[_currentFrame];
		_time = _anim._frames_loop_time[_currentFrame];
		
		_matrix = new Matrix (1, 0, 0, 1, 0, 0);
		
		addEventListener (Event.ENTER_FRAME, function (e:Event):Void {update(); render();});
	}
	
	public function update ():Void
	{
		if (--_time > 0) return;
		else
		{
			if (++_currentFrame >= _nFrame) _currentFrame = 0;
			
			_frameId = _anim._frames_id[_currentFrame];
			_time = _anim._frames_loop_time[_currentFrame];
			_bound = _sprite._frames.get (_frameId)._bound.clone();
			_matrix.tx = _bound.x;
			_matrix.ty = _bound.y;
			
			_changed = true;
		}
	}
	
	public function render ():Void
	{
		if (!_changed) return;
		else _changed = false;
		
		var frame:FrameData = _sprite._frames.get (_frameId);
		
		graphics.clear ();
		// frame.toGraphics (graphics);
		// graphics.beginFill (0xFF0000, 0.25);
		// graphics.drawRect (-30, -30, 60, 60);
		graphics.drawTiles (_sprite._tileSheet, frame.getTileData (), true, Tilesheet.TILE_TRANS_2x2);
	}
}